<?php

namespace app\services;


use app\BaseController;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JWTUtil;
use Firebase\JWT\Key;

class Jwt
{
    /**
     * 根据json web token设置的规则生成token
     * @return \think\response\Json
     */
    public static function createjwt($id)
    {
        //jwt的签发密钥，验证token的时候需要用到
        $key = md5('pyg');
        //签发时间
        $time = time();
        //过期时间
        $expire = $time + 1440000;
        $token = array(
            "user_id" => $id,
            "iss" => "car.ydk1.cn",//签发组织
            "aud" => "fsc123", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
        $jwt = JWTUtil::encode($token,$key,'HS256');
        return $jwt;
    }

    /**
     * 验证token
     * @param $token
     * @return array
     */
    public static function verifyjwt($token)
    {

        $key = md5('pyg'); //jwt的签发密钥，验证token的时候需要用到
        try{
            $jwtAuth = json_encode(JWTUtil::decode($token, new Key($key, 'HS256')));
            $authInfo = json_decode($jwtAuth,true);
            if (!$authInfo['user_id']){
                return ['status'=>false,'msg'=>"用户不存在"];
            }
            return ['status'=>true,'id'=>$authInfo['user_id']];
        }catch (ExpiredException $e){
            return ['status'=>false,'msg'=>"token过期"];
        }catch (\Exception $e){
            return ['status'=>false,'msg'=>'请重新登录'];
        }

    }

}